<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="800px"
    class="ai-chat-dialog"
    :before-close="handleClose"
    destroy-on-close
  >
    <!-- 聊天消息区域 -->
    <div class="chat-container">
      <div ref="messagesContainer" class="messages-container">
        <div
          v-for="(message, index) in messages"
          :key="index"
          class="message-item"
          :class="message.type"
        >
          <div class="message-content">
            <div v-if="message.type === 'user'" class="user-message">
              <div class="message-text">{{ message.content }}</div>
              <div class="message-avatar">
                <el-icon><User /></el-icon>
              </div>
            </div>
            <div v-else class="ai-message" :data-streaming="message.streaming">
              <div class="message-avatar ai-avatar">
                <el-icon><ChatDotSquare /></el-icon>
              </div>
              <div class="message-text">
                <!-- AI思考内容（折叠展示） -->
                <div v-if="message.thinkingContent" class="thinking-section">
                  <div 
                    class="thinking-header" 
                    @click="message.showThinking = !message.showThinking"
                  >
                    <el-icon class="thinking-icon">
                      <span v-if="message.showThinking">▼</span>
                      <span v-else>▶</span>
                    </el-icon>
                    <span class="thinking-label">💭 AI思考过程</span>
                    <span class="thinking-hint">（点击查看）</span>
                  </div>
                  <div 
                    v-show="message.showThinking" 
                    class="thinking-content"
                  >
                    <div v-html="renderMarkdown(message.thinkingContent)"></div>
                  </div>
                </div>

                <!-- 支持文字和图片展示 -->
                <div v-if="message.contentType === 'text'" class="text-content">
                  <div v-html="renderMarkdown(message.content)"></div>
                  <!-- 流式输出时显示光标 -->
                  <span v-if="message.streaming" class="streaming-cursor">|</span>
                </div>
                <div v-else-if="message.contentType === 'image'" class="image-content">
                  <el-image
                    :src="message.content"
                    :preview-src-list="[message.content]"
                    fit="cover"
                    class="message-image"
                  />
                </div>
                <div v-else-if="message.contentType === 'mixed'" class="mixed-content">
                  <div v-if="message.text" v-html="renderMarkdown(message.text)"></div>
                  <el-image
                    v-if="message.image"
                    :src="message.image"
                    :preview-src-list="[message.image]"
                    fit="cover"
                    class="message-image"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
        
        <!-- 流式输出状态提示 -->
        <div v-if="loading && !currentStreamingMessage" class="message-item ai">
          <div class="message-content">
            <div class="ai-message">
              <div class="message-avatar ai-avatar">
                <el-icon><ChatDotSquare /></el-icon>
              </div>
              <div class="message-text">
                <div class="preparing-response">
                  正在思考中...
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <!-- 表单区域 -->
      <div 
        v-if="!isNoFormExpert()" 
        class="form-container"
      >
        <div class="form-header" @click="showFormFields = !showFormFields">
          <span class="form-title">📝 {{ getFormTitle() }}（选填）</span>
          <el-icon class="form-toggle">
            <span v-if="showFormFields">▼</span>
            <span v-else>▶</span>
          </el-icon>
        </div>
        
        <div v-show="showFormFields" class="form-fields">
          <!-- AI诊断专家表单 -->
          <el-form v-if="dialogTitle === 'AI诊断专家'" :model="aiDiagnosisFormData" label-width="120px" size="small">
            <div class="form-row">
              <el-form-item label="产品名称" class="form-item-half">
                <el-input v-model="aiDiagnosisFormData.productName" placeholder="请输入产品名称" clearable />
              </el-form-item>
              <el-form-item label="产品类别" class="form-item-half">
                <el-select v-model="aiDiagnosisFormData.productCategory" placeholder="请选择产品类别" clearable>
                  <el-option label="电商" value="电商" />
                  <el-option label="教育培训" value="教育培训" />
                  <el-option label="金融服务" value="金融服务" />
                  <el-option label="本地生活" value="本地生活" />
                  <el-option label="游戏娱乐" value="游戏娱乐" />
                  <el-option label="汽车" value="汽车" />
                  <el-option label="房产家居" value="房产家居" />
                  <el-option label="医疗健康" value="医疗健康" />
                  <el-option label="旅游出行" value="旅游出行" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </div>
            
            <el-form-item label="核心卖点">
              <el-input 
                v-model="aiDiagnosisFormData.coreSellingPoint" 
                type="textarea" 
                :rows="2" 
                placeholder="请描述产品的核心优势和卖点" 
                clearable 
              />
            </el-form-item>
            
            <div class="form-row">
              <el-form-item label="目标受众年龄" class="form-item-half">
                <el-select v-model="aiDiagnosisFormData.targetAgeRange" placeholder="请选择年龄范围" clearable>
                  <el-option label="18-25岁" value="18-25" />
                  <el-option label="26-35岁" value="26-35" />
                  <el-option label="36-45岁" value="36-45" />
                  <el-option label="46-55岁" value="46-55" />
                  <el-option label="55岁以上" value="55+" />
                  <el-option label="不限" value="不限" />
                </el-select>
              </el-form-item>
              <el-form-item label="目标地区" class="form-item-half">
                <el-input v-model="aiDiagnosisFormData.targetRegion" placeholder="如：北京、上海、全国等" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="广告预算" class="form-item-half">
                <el-select v-model="aiDiagnosisFormData.adBudget" placeholder="请选择预算范围" clearable>
                  <el-option label="1000元以下/天" value="<1000" />
                  <el-option label="1000-5000元/天" value="1000-5000" />
                  <el-option label="5000-10000元/天" value="5000-10000" />
                  <el-option label="10000-20000元/天" value="10000-20000" />
                  <el-option label="20000元以上/天" value="20000+" />
                </el-select>
              </el-form-item>
              <el-form-item label="活动周期" class="form-item-half">
                <el-select v-model="aiDiagnosisFormData.campaignDuration" placeholder="请选择活动周期" clearable>
                  <el-option label="1周以内" value="1周以内" />
                  <el-option label="1-2周" value="1-2周" />
                  <el-option label="2-4周" value="2-4周" />
                  <el-option label="1-3个月" value="1-3个月" />
                  <el-option label="3个月以上" value="3个月以上" />
                  <el-option label="长期投放" value="长期投放" />
                </el-select>
              </el-form-item>
            </div>
            
            <el-form-item label="核心目标">
              <el-select v-model="aiDiagnosisFormData.coreGoal" placeholder="请选择核心目标" clearable>
                <el-option label="品牌曝光" value="品牌曝光" />
                <el-option label="获取线索" value="获取线索" />
                <el-option label="促进销售" value="促进销售" />
                <el-option label="用户注册" value="用户注册" />
                <el-option label="应用下载" value="应用下载" />
                <el-option label="客户咨询" value="客户咨询" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-form>

          <!-- 目标客群画像表单 -->
          <el-form v-else-if="dialogTitle === '目标客群画像'" :model="targetAudienceFormData" label-width="120px" size="small">
            <div class="form-row">
              <el-form-item label="行业" class="form-item-half">
                <el-select v-model="targetAudienceFormData.industry" placeholder="请选择行业" clearable>
                  <el-option label="电商零售" value="电商零售" />
                  <el-option label="教育培训" value="教育培训" />
                  <el-option label="金融保险" value="金融保险" />
                  <el-option label="医疗健康" value="医疗健康" />
                  <el-option label="汽车服务" value="汽车服务" />
                  <el-option label="房产家居" value="房产家居" />
                  <el-option label="美妆护肤" value="美妆护肤" />
                  <el-option label="餐饮美食" value="餐饮美食" />
                  <el-option label="旅游出行" value="旅游出行" />
                  <el-option label="游戏娱乐" value="游戏娱乐" />
                  <el-option label="母婴用品" value="母婴用品" />
                  <el-option label="服装配饰" value="服装配饰" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
              <el-form-item label="产品类型" class="form-item-half">
                <el-select v-model="targetAudienceFormData.productType" placeholder="请选择产品类型" clearable>
                  <el-option label="实物商品" value="实物商品" />
                  <el-option label="数字产品" value="数字产品" />
                  <el-option label="服务类" value="服务类" />
                  <el-option label="软件应用" value="软件应用" />
                  <el-option label="课程培训" value="课程培训" />
                  <el-option label="咨询服务" value="咨询服务" />
                </el-select>
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="目标地域" class="form-item-half">
                <el-input v-model="targetAudienceFormData.targetArea" placeholder="如：一线城市、江浙沪、全国等" clearable />
              </el-form-item>
              <el-form-item label="核心功能" class="form-item-half">
                <el-input v-model="targetAudienceFormData.coreFunction" placeholder="产品的主要功能或解决的问题" clearable />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="价格区间" class="form-item-half">
                <el-select v-model="targetAudienceFormData.priceRange" placeholder="请选择价格区间" clearable>
                  <el-option label="100元以下" value="<100" />
                  <el-option label="100-500元" value="100-500" />
                  <el-option label="500-1000元" value="500-1000" />
                  <el-option label="1000-5000元" value="1000-5000" />
                  <el-option label="5000-10000元" value="5000-10000" />
                  <el-option label="10000元以上" value="10000+" />
                </el-select>
              </el-form-item>
              <el-form-item label="销售渠道" class="form-item-half">
                <el-select v-model="targetAudienceFormData.salesChannel" placeholder="请选择销售渠道" clearable>
                  <el-option label="线上电商" value="线上电商" />
                  <el-option label="线下门店" value="线下门店" />
                  <el-option label="官方网站" value="官方网站" />
                  <el-option label="微信小程序" value="微信小程序" />
                  <el-option label="APP" value="APP" />
                  <el-option label="线上+线下" value="线上+线下" />
                </el-select>
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="年龄范围" class="form-item-half">
                <el-select v-model="targetAudienceFormData.ageRange" placeholder="请选择年龄范围" clearable>
                  <el-option label="18-25岁" value="18-25" />
                  <el-option label="26-35岁" value="26-35" />
                  <el-option label="36-45岁" value="36-45" />
                  <el-option label="46-55岁" value="46-55" />
                  <el-option label="55岁以上" value="55+" />
                  <el-option label="全年龄" value="全年龄" />
                </el-select>
              </el-form-item>
              <el-form-item label="性别" class="form-item-half">
                <el-select v-model="targetAudienceFormData.gender" placeholder="请选择目标性别" clearable>
                  <el-option label="男性" value="男性" />
                  <el-option label="女性" value="女性" />
                  <el-option label="不限" value="不限" />
                </el-select>
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="目标地区" class="form-item-half">
                <el-input v-model="targetAudienceFormData.targetRegion" placeholder="具体投放地区" clearable />
              </el-form-item>
              <el-form-item label="职业" class="form-item-half">
                <el-select v-model="targetAudienceFormData.occupation" placeholder="请选择目标职业" clearable>
                  <el-option label="学生" value="学生" />
                  <el-option label="上班族" value="上班族" />
                  <el-option label="企业主" value="企业主" />
                  <el-option label="自由职业" value="自由职业" />
                  <el-option label="退休人员" value="退休人员" />
                  <el-option label="家庭主妇" value="家庭主妇" />
                  <el-option label="不限" value="不限" />
                </el-select>
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="收入水平" class="form-item-half">
                <el-select v-model="targetAudienceFormData.incomeLevel" placeholder="请选择收入水平" clearable>
                  <el-option label="3000元以下" value="<3000" />
                  <el-option label="3000-8000元" value="3000-8000" />
                  <el-option label="8000-15000元" value="8000-15000" />
                  <el-option label="15000-30000元" value="15000-30000" />
                  <el-option label="30000元以上" value="30000+" />
                  <el-option label="不限" value="不限" />
                </el-select>
              </el-form-item>
              <el-form-item label="参考目标" class="form-item-half">
                <el-select v-model="targetAudienceFormData.referenceGoal" placeholder="请选择参考目标" clearable>
                  <el-option label="品牌知名度" value="品牌知名度" />
                  <el-option label="销售转化" value="销售转化" />
                  <el-option label="用户获取" value="用户获取" />
                  <el-option label="流量增长" value="流量增长" />
                  <el-option label="互动参与" value="互动参与" />
                </el-select>
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="兴趣" class="form-item-half">
                <el-input v-model="targetAudienceFormData.interests" placeholder="目标用户的兴趣爱好" clearable />
              </el-form-item>
              <el-form-item label="渠道" class="form-item-half">
                <el-select v-model="targetAudienceFormData.channel" placeholder="请选择投放渠道" clearable>
                  <el-option label="抖音" value="抖音" />
                  <el-option label="快手" value="快手" />
                  <el-option label="小红书" value="小红书" />
                  <el-option label="微信朋友圈" value="微信朋友圈" />
                  <el-option label="今日头条" value="今日头条" />
                  <el-option label="百度信息流" value="百度信息流" />
                  <el-option label="腾讯广告" value="腾讯广告" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </div>

            <el-form-item label="使用场景">
              <el-input 
                v-model="targetAudienceFormData.useScenario" 
                type="textarea" 
                :rows="2" 
                placeholder="描述用户使用产品的典型场景" 
                clearable 
              />
            </el-form-item>
          </el-form>

          <!-- 广告活动策划表单 -->
          <el-form v-else-if="dialogTitle === '广告活动策划'" :model="campaignPlanningFormData" label-width="120px" size="small">
            <div class="form-row">
              <el-form-item label="活动名称" class="form-item-half">
                <el-input v-model="campaignPlanningFormData.name" placeholder="请输入活动名称" clearable />
              </el-form-item>
              <el-form-item label="活动类型" class="form-item-half">
                <el-select v-model="campaignPlanningFormData.type" placeholder="请选择活动类型" clearable>
                  <el-option label="线上活动" value="线上活动" />
                  <el-option label="线下活动" value="线下活动" />
                  <el-option label="混合活动" value="混合活动" />
                </el-select>
              </el-form-item>
            </div>
            
            <el-form-item label="核心卖点">
              <el-input 
                v-model="campaignPlanningFormData.sellingPoint" 
                type="textarea" 
                :rows="2" 
                placeholder="请描述活动的核心卖点" 
                clearable 
              />
            </el-form-item>
            
            <div class="form-row">
              <el-form-item label="品牌价值" class="form-item-half">
                <el-input 
                  v-model="campaignPlanningFormData.brandValue" 
                  type="textarea" 
                  :rows="2" 
                  placeholder="请描述活动的品牌价值" 
                  clearable 
                />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="年龄" class="form-item-half">
                <el-select v-model="campaignPlanningFormData.age" placeholder="请选择目标年龄" clearable>
                  <el-option label="18-25岁" value="18-25" />
                  <el-option label="26-35岁" value="26-35" />
                  <el-option label="36-45岁" value="36-45" />
                  <el-option label="46-55岁" value="46-55" />
                  <el-option label="55岁以上" value="55+" />
                </el-select>
              </el-form-item>
              <el-form-item label="性别" class="form-item-half">
                <el-select v-model="campaignPlanningFormData.gender" placeholder="请选择目标性别" clearable>
                  <el-option label="男性" value="男性" />
                  <el-option label="女性" value="女性" />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="地区" class="form-item-half">
                <el-input v-model="campaignPlanningFormData.region" placeholder="请输入目标地区" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="兴趣标签" class="form-item-half">
                <el-input v-model="campaignPlanningFormData.interestTags" placeholder="请输入兴趣标签" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="总预算" class="form-item-half">
                <el-input v-model="campaignPlanningFormData.totalBudget" placeholder="请输入总预算" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="主要周期" class="form-item-half">
                <el-select v-model="campaignPlanningFormData.mainPeriod" placeholder="请选择主要周期" clearable>
                  <el-option label="1周以内" value="1周以内" />
                  <el-option label="1-2周" value="1-2周" />
                  <el-option label="2-4周" value="2-4周" />
                  <el-option label="1-3个月" value="1-3个月" />
                  <el-option label="3个月以上" value="3个月以上" />
                </el-select>
              </el-form-item>
              <el-form-item label="预热周期" class="form-item-half">
                <el-select v-model="campaignPlanningFormData.warmupPeriod" placeholder="请选择预热周期" clearable>
                  <el-option label="1周以内" value="1周以内" />
                  <el-option label="1-2周" value="1-2周" />
                  <el-option label="2-4周" value="2-4周" />
                  <el-option label="1-3个月" value="1-3个月" />
                  <el-option label="3个月以上" value="3个月以上" />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="竞争对手品牌" class="form-item-half">
                <el-input v-model="campaignPlanningFormData.competitorBrands" placeholder="请输入竞争对手品牌" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="首选渠道" class="form-item-half">
                <el-input v-model="campaignPlanningFormData.preferredChannel" placeholder="请输入首选渠道" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="目标KPI" class="form-item-half">
                <el-input v-model="campaignPlanningFormData.targetKPI" placeholder="请输入目标KPI" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="品牌" class="form-item-half">
                <el-input v-model="campaignPlanningFormData.brand" placeholder="请输入品牌" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="受众兴趣标签" class="form-item-half">
                <el-input v-model="campaignPlanningFormData.audienceInterestTags" placeholder="请输入受众兴趣标签" clearable />
              </el-form-item>
            </div>
          </el-form>

          <!-- AI标题生成器表单 -->
          <el-form v-else-if="dialogTitle === 'AI标题生成器'" :model="titleGeneratorFormData" label-width="120px" size="small">
            <div class="form-row">
              <el-form-item label="产品名称" class="form-item-half">
                <el-input v-model="titleGeneratorFormData.productName" placeholder="请输入产品名称" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="目标受众" class="form-item-half">
                <el-input v-model="titleGeneratorFormData.targetAudience" placeholder="请描述目标受众" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="核心卖点" class="form-item-half">
                <el-input v-model="titleGeneratorFormData.coreSellingPoint" placeholder="请描述核心卖点" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="品牌调性" class="form-item-half">
                <el-input v-model="titleGeneratorFormData.brandTone" placeholder="请描述品牌调性" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="关键词" class="form-item-half">
                <el-input v-model="titleGeneratorFormData.keywords" placeholder="请输入关键词" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="字符限制" class="form-item-half">
                <el-input v-model="titleGeneratorFormData.characterLimit" placeholder="请输入字符限制" clearable />
              </el-form-item>
            </div>
          </el-form>

          <!-- AI媒体文案表单 -->
          <el-form v-else-if="dialogTitle === 'AI媒体文案'" :model="mediaCopyFormData" label-width="120px" size="small">
            <div class="form-row">
              <el-form-item label="产品名称" class="form-item-half">
                <el-input v-model="mediaCopyFormData.productName" placeholder="请输入产品名称" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="目标受众" class="form-item-half">
                <el-input v-model="mediaCopyFormData.targetAudience" placeholder="请描述目标受众" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="核心卖点" class="form-item-half">
                <el-input v-model="mediaCopyFormData.keySellingPoint" placeholder="请描述核心卖点" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="使用场景" class="form-item-half">
                <el-input v-model="mediaCopyFormData.useScenario" placeholder="请描述使用场景" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="行动号召" class="form-item-half">
                <el-input v-model="mediaCopyFormData.callToAction" placeholder="请输入行动号召" clearable />
              </el-form-item>
            </div>
            
            <div class="form-row">
              <el-form-item label="字数限制" class="form-item-half">
                <el-input v-model="mediaCopyFormData.wordLimit" placeholder="请输入字数限制" clearable />
              </el-form-item>
            </div>
          </el-form>

          <!-- AI落地页搭建表单 -->
          <el-form v-else-if="dialogTitle === 'AI落地页搭建'" :model="landingPageFormData" label-width="120px" size="small">
            <div class="form-row">
              <el-form-item label="行业类型" class="form-item-half">
                <el-select v-model="landingPageFormData.industryType" placeholder="请选择行业类型" clearable>
                  <el-option label="电商" value="电商" />
                  <el-option label="教育培训" value="教育培训" />
                  <el-option label="金融服务" value="金融服务" />
                  <el-option label="本地生活" value="本地生活" />
                  <el-option label="游戏娱乐" value="游戏娱乐" />
                  <el-option label="汽车" value="汽车" />
                  <el-option label="房产家居" value="房产家居" />
                  <el-option label="医疗健康" value="医疗健康" />
                  <el-option label="旅游出行" value="旅游出行" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
              <el-form-item label="产品类型" class="form-item-half">
                <el-select v-model="landingPageFormData.productType" placeholder="请选择产品类型" clearable>
                  <el-option label="实物商品" value="实物商品" />
                  <el-option label="数字产品" value="数字产品" />
                  <el-option label="服务类" value="服务类" />
                  <el-option label="软件应用" value="软件应用" />
                  <el-option label="课程培训" value="课程培训" />
                  <el-option label="咨询服务" value="咨询服务" />
                </el-select>
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="目标受众" class="form-item-half">
                <el-input v-model="landingPageFormData.targetAudience" placeholder="请描述目标受众" clearable />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="核心转化目标" class="form-item-half">
                <el-input v-model="landingPageFormData.coreConversionGoal" placeholder="请描述核心转化目标" clearable />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="预算范围" class="form-item-half">
                <el-input v-model="landingPageFormData.budgetRange" placeholder="请输入预算范围" clearable />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="平台" class="form-item-half">
                <el-input v-model="landingPageFormData.platform" placeholder="请输入平台" clearable />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="行业特点" class="form-item-half">
                <el-input v-model="landingPageFormData.industryFeatures" placeholder="请描述行业特点" clearable />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="监管限制" class="form-item-half">
                <el-input v-model="landingPageFormData.regulatoryLimitations" placeholder="请描述监管限制" clearable />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="品牌视觉指南" class="form-item-half">
                <el-input v-model="landingPageFormData.brandVisualGuidelines" placeholder="请描述品牌视觉指南" clearable />
              </el-form-item>
            </div>

            <div class="form-row">
              <el-form-item label="历史数据参考" class="form-item-half">
                <el-input v-model="landingPageFormData.historicalDataReference" placeholder="请输入历史数据参考" clearable />
              </el-form-item>
            </div>
          </el-form>

          <!-- 其他专家表单（默认为基础表单） -->
          <el-form v-else :model="basicFormData" label-width="120px" size="small">
            <div class="form-row">
              <el-form-item label="产品/服务" class="form-item-half">
                <el-input v-model="basicFormData.productService" placeholder="请输入产品或服务名称" clearable />
              </el-form-item>
              <el-form-item label="目标受众" class="form-item-half">
                <el-input v-model="basicFormData.targetAudience" placeholder="请描述目标受众" clearable />
              </el-form-item>
            </div>
            
            <el-form-item label="核心需求">
              <el-input 
                v-model="basicFormData.coreRequirement" 
                type="textarea" 
                :rows="2" 
                placeholder="请描述您的核心需求" 
                clearable 
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <div class="input-wrapper">
        <el-input
          v-model="inputText"
          type="textarea"
          :rows="3"
          placeholder="请输入您的问题，AI诊断专家将为您提供专业的广告优化建议..."
          :maxlength="500"
          show-word-limit
          resize="none"
          @keyup.ctrl.enter="sendMessage"
        />
        <el-button
          type="primary"
          :loading="loading"
          :disabled="!inputText.trim()"
          @click="sendMessage"
          class="send-button"
        >
          <el-icon><Promotion /></el-icon>
          发送
        </el-button>
      </div>
      <div class="input-tips">
        <span>按 Ctrl + Enter 发送消息</span>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { User, ChatDotSquare, Promotion } from '@element-plus/icons-vue'
// import marked from 'marked'
// import DOMPurify from 'dompurify'
import { sendAiChatStreamMessage, mockAiStreamResponse } from '@/api/ai-chat'

interface ChatMessage {
  id: string
  type: 'user' | 'ai'
  content: string
  contentType: 'text' | 'image' | 'mixed'
  text?: string
  image?: string
  timestamp: Date
  streaming?: boolean // 标识是否正在流式输出
  thinkingContent?: string // AI思考内容
  showThinking?: boolean // 是否显示思考内容
}

const props = defineProps<{
  modelValue: boolean
  title?: string
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 动态对话框标题
const dialogTitle = computed(() => props.title || 'AI诊断专家')


const messages = ref<ChatMessage[]>([])
const inputText = ref('')
const loading = ref(false)
const messagesContainer = ref<HTMLElement>()
const currentStreamingMessage = ref<ChatMessage | null>(null) // 当前正在流式输出的消息
const streamBuffer = ref('') // 流式输出缓冲区
const isInThinking = ref(false) // 是否在思考标签内
const thinkingBuffer = ref('') // 思考内容缓冲区
const showFormFields = ref(false)

// AI诊断专家表单数据
const aiDiagnosisFormData = ref({
  productName: '',
  productCategory: '',
  coreSellingPoint: '',
  targetAgeRange: '',
  targetRegion: '',
  adBudget: '',
  campaignDuration: '',
  coreGoal: ''
})

// 信息流策划专家表单数据
const feedPlannerFormData = ref({
  industry: '',
  productType: '',
  targetArea: '',
  coreFunction: '',
  priceRange: '',
  salesChannel: '',
  ageRange: '',
  gender: '',
  targetRegion: '',
  occupation: '',
  incomeLevel: '',
  referenceGoal: '',
  interests: '',
  channel: '',
  useScenario: ''
})

// 目标客群画像表单数据
const targetAudienceFormData = ref({
  industry: '',
  productType: '',
  targetArea: '',
  coreFunction: '',
  priceRange: '',
  salesChannel: '',
  ageRange: '',
  gender: '',
  targetRegion: '',
  occupation: '',
  incomeLevel: '',
  referenceGoal: '',
  interests: '',
  channel: '',
  useScenario: ''
})

// 广告活动策划表单数据
const campaignPlanningFormData = ref({
  name: '',
  type: '',
  sellingPoint: '',
  brandValue: '',
  age: '',
  gender: '',
  region: '',
  interestTags: '',
  totalBudget: '',
  mainPeriod: '',
  warmupPeriod: '',
  competitorBrands: '',
  preferredChannel: '',
  targetKPI: '',
  brand: '',
  audienceInterestTags: ''
})

// AI标题生成器表单数据
const titleGeneratorFormData = ref({
  productName: '',
  targetAudience: '',
  coreSellingPoint: '',
  brandTone: '',
  keywords: '',
  characterLimit: ''
})

// AI媒体文案表单数据
const mediaCopyFormData = ref({
  productName: '',
  targetAudience: '',
  keySellingPoint: '',
  useScenario: '',
  callToAction: '',
  wordLimit: ''
})

// AI落地页搭建表单数据
const landingPageFormData = ref({
  industryType: '',
  productType: '',
  targetAudience: '',
  coreConversionGoal: '',
  budgetRange: '',
  platform: '',
  industryFeatures: '',
  regulatoryLimitations: '',
  brandVisualGuidelines: '',
  historicalDataReference: ''
})

// 基础表单数据（其他专家使用）
const basicFormData = ref({
  productService: '',
  targetAudience: '',
  coreRequirement: ''
})

// 获取表单标题
const getFormTitle = () => {
  const titleMap: Record<string, string> = {
    'AI诊断专家': '广告项目信息',
    '目标客群画像': '客群画像详情',
    '广告活动策划': '活动策划信息',
    '每日数据复盘': '数据复盘信息',
    '转化率诊断': '转化分析信息',
    '客群精准度分析': '客群分析信息',
    '私域承接力评估': '私域运营信息',
    'AI标题生成器': '标题生成信息',
    'AI媒体文案': '媒体文案信息',
    'AI落地页搭建': '落地页搭建信息'
  }
  return titleMap[dialogTitle.value] || '项目信息'
}

// 获取当前使用的表单数据
const getCurrentFormData = () => {
  switch (dialogTitle.value) {
    case 'AI诊断专家':
      return aiDiagnosisFormData.value
    case '目标客群画像':
      return targetAudienceFormData.value
    case '广告活动策划':
      return campaignPlanningFormData.value
    case 'AI标题生成器':
      return titleGeneratorFormData.value
    case 'AI媒体文案':
      return mediaCopyFormData.value
    case 'AI落地页搭建':
      return landingPageFormData.value
    default:
      return basicFormData.value
  }
}

// 判断是否为不需要表单的专家
const isNoFormExpert = () => {
  const noFormExperts = [
    '每日数据复盘',
    '转化率诊断', 
    '客群精准度分析',
    '私域承接力评估'
  ]
  return noFormExperts.includes(dialogTitle.value)
}

// 初始化欢迎消息
const initWelcomeMessage = () => {
  const expertName = props.title || 'AI诊断专家'
  messages.value = [{
    id: Date.now().toString(),
    type: 'ai',
    content: `您好！我是${expertName} 🤖

我可以帮助您：
- 📊 分析广告投放数据
- 🎯 优化广告策略建议  
- 💰 降低投放成本建议
- 📈 提升转化率方案
- 🔍 诊断账户问题

请告诉我您遇到的问题，我将为您提供专业的诊断和建议！`,
    contentType: 'text',
    timestamp: new Date(),
    streaming: false,
    thinkingContent: '',
    showThinking: false
  }]
}

// 渲染 Markdown
const renderMarkdown = (content: string) => {
  try {
    // 暂时不使用marked，直接返回内容
    // const html = marked.parse(content) as string
    // return DOMPurify.sanitize(html)
    return content
  } catch (error) {
    console.error('Markdown render error:', error)
    return content
  }
}

// 格式化时间
const formatTime = (date: Date) => {
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 解析流式输出中的思考标签
const parseStreamContent = (chunk: string) => {
  streamBuffer.value += chunk
  
  // 检查是否有完整的 think 标签
  const thinkStartMatch = streamBuffer.value.match(/<think>/g)
  const thinkEndMatch = streamBuffer.value.match(/<\/think>/g)
  
  if (thinkStartMatch && thinkEndMatch && thinkStartMatch.length === thinkEndMatch.length) {
    // 有完整的思考标签，解析内容
    const thinkRegex = /<think>([\s\S]*?)<\/think>/g
    let match
    let processedContent = streamBuffer.value
    
    while ((match = thinkRegex.exec(streamBuffer.value)) !== null) {
      const thinkingContent = match[1].trim()
      if (currentStreamingMessage.value && thinkingContent) {
        currentStreamingMessage.value.thinkingContent = thinkingContent
        currentStreamingMessage.value.showThinking = false
      }
      // 从内容中移除思考标签
      processedContent = processedContent.replace(match[0], '')
    }
    
    if (currentStreamingMessage.value) {
      currentStreamingMessage.value.content = processedContent.trim()
    }
    
    streamBuffer.value = ''
  } else if (currentStreamingMessage.value) {
    // 没有完整的思考标签，直接显示内容
    if (!streamBuffer.value.includes('<think>')) {
      currentStreamingMessage.value.content = streamBuffer.value
    }
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputText.value.trim() || loading.value) return

  const userMessage: ChatMessage = {
    id: Date.now().toString(),
    type: 'user',
    content: inputText.value.trim(),
    contentType: 'text',
    timestamp: new Date(),
    streaming: false
  }

  messages.value.push(userMessage)
  const messageContent = inputText.value.trim()
  inputText.value = ''
  
  scrollToBottom()

  try {
    loading.value = true
    
    // 创建AI响应消息
    const aiMessage: ChatMessage = {
      id: `ai_${Date.now()}`,
      type: 'ai',
      content: '',
      contentType: 'text',
      timestamp: new Date(),
      streaming: true,
      thinkingContent: '',
      showThinking: false
    }
    
    messages.value.push(aiMessage)
    currentStreamingMessage.value = aiMessage
    streamBuffer.value = '' // 清空缓冲区
    scrollToBottom()

    // 构建发送的数据，包含消息内容和表单数据
    const requestData = {
      message: messageContent,
      formData: getCurrentFormData()
    }

    // 使用流式响应，传递包含表单数据的对象
    await sendAiChatStreamMessage(
      requestData, // 传递包含表单数据的对象
      dialogTitle.value,
      // onChunk - 接收流式数据块
      (chunk: string) => {
        parseStreamContent(chunk)
        scrollToBottom()
      },
      // onFinished - 流式输出完成
      () => {
        if (currentStreamingMessage.value) {
          currentStreamingMessage.value.streaming = false
          currentStreamingMessage.value = null
        }
        streamBuffer.value = '' // 清空缓冲区
        loading.value = false
        scrollToBottom()
      },
      // onError - 发生错误
      (error: Error) => {
        console.error('流式输出失败:', error)
        ElMessage.error('发送失败，请稍后重试')
        
        if (currentStreamingMessage.value) {
          currentStreamingMessage.value.content = '抱歉，网络连接异常，请稍后重试。'
          currentStreamingMessage.value.streaming = false
          currentStreamingMessage.value = null
        }
        streamBuffer.value = '' // 清空缓冲区
        loading.value = false
        scrollToBottom()
      }
    )
    
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败，请稍后重试')
    
    if (currentStreamingMessage.value) {
      currentStreamingMessage.value.content = '抱歉，网络连接异常，请稍后重试。'
      currentStreamingMessage.value.streaming = false
      currentStreamingMessage.value = null
    }
    loading.value = false
    scrollToBottom()
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 监听对话框打开，清空并初始化欢迎消息
watch(visible, (newValue) => {
  if (newValue) {
    // 每次打开都清空之前的会话内容
    messages.value = []
    // 重置所有表单数据
    aiDiagnosisFormData.value = {
      productName: '',
      productCategory: '',
      coreSellingPoint: '',
      targetAgeRange: '',
      targetRegion: '',
      adBudget: '',
      campaignDuration: '',
      coreGoal: ''
    }
    feedPlannerFormData.value = {
      industry: '',
      productType: '',
      targetArea: '',
      coreFunction: '',
      priceRange: '',
      salesChannel: '',
      ageRange: '',
      gender: '',
      targetRegion: '',
      occupation: '',
      incomeLevel: '',
      referenceGoal: '',
      interests: '',
      channel: '',
      useScenario: ''
    }
    targetAudienceFormData.value = {
      industry: '',
      productType: '',
      targetArea: '',
      coreFunction: '',
      priceRange: '',
      salesChannel: '',
      ageRange: '',
      gender: '',
      targetRegion: '',
      occupation: '',
      incomeLevel: '',
      referenceGoal: '',
      interests: '',
      channel: '',
      useScenario: ''
    }
    campaignPlanningFormData.value = {
      name: '',
      type: '',
      sellingPoint: '',
      brandValue: '',
      age: '',
      gender: '',
      region: '',
      interestTags: '',
      totalBudget: '',
      mainPeriod: '',
      warmupPeriod: '',
      competitorBrands: '',
      preferredChannel: '',
      targetKPI: '',
      brand: '',
      audienceInterestTags: ''
    }
    titleGeneratorFormData.value = {
      productName: '',
      targetAudience: '',
      coreSellingPoint: '',
      brandTone: '',
      keywords: '',
      characterLimit: ''
    }
    mediaCopyFormData.value = {
      productName: '',
      targetAudience: '',
      keySellingPoint: '',
      useScenario: '',
      callToAction: '',
      wordLimit: ''
    }
    landingPageFormData.value = {
      industryType: '',
      productType: '',
      targetAudience: '',
      coreConversionGoal: '',
      budgetRange: '',
      platform: '',
      industryFeatures: '',
      regulatoryLimitations: '',
      brandVisualGuidelines: '',
      historicalDataReference: ''
    }
    basicFormData.value = {
      productService: '',
      targetAudience: '',
      coreRequirement: ''
    }
    showFormFields.value = false
    // 重新初始化欢迎消息
    initWelcomeMessage()
    nextTick(() => {
      scrollToBottom()
    })
  }
})
</script>

<style scoped>
.ai-chat-dialog {
  --el-dialog-bg-color: #fff;
}

.chat-container {
  height: 500px;
  display: flex;
  flex-direction: column;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.message-item {
  margin-bottom: 16px;
  width: 100%;
  display: flex;
  flex-direction: column;
}

.message-item.user {
  align-items: flex-end;
}

.message-item.ai {
  align-items: flex-start;
}

.message-content {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  width: 100%;
}

.user-message {
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  gap: 12px;
  margin-left: auto;
  max-width: 80%;
}

.ai-message {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-right: auto;
  max-width: 80%;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.message-avatar {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.ai-avatar {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.message-text {
  padding: 12px 16px;
  border-radius: 12px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  line-height: 1.5;
  word-wrap: break-word;
  flex: 1;
  min-width: 0;
}

.user-message .message-text {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  color: white;
  border-radius: 12px 12px 4px 12px;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.3);
}

.ai-message .message-text {
  background-color: white;
  color: #333;
  border-radius: 12px 12px 12px 4px;
  border: 1px solid #e5e7eb;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  padding: 0 12px;
}

.message-item.user .message-time {
  text-align: right;
}

.message-item.ai .message-time {
  text-align: left;
}

.text-content :deep(h1),
.text-content :deep(h2),
.text-content :deep(h3) {
  margin: 12px 0 8px 0;
  color: #333;
}

.text-content :deep(p) {
  margin: 8px 0;
}

.text-content :deep(ul),
.text-content :deep(ol) {
  margin: 8px 0;
  padding-left: 20px;
}

.text-content :deep(code) {
  background-color: #f5f5f5;
  padding: 2px 4px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
}

.text-content :deep(pre) {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 8px 0;
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  margin-top: 8px;
  cursor: pointer;
}

.mixed-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 流式输出光标动画 */
.streaming-cursor {
  display: inline-block;
  color: #409eff;
  font-weight: bold;
  animation: blink 1s infinite;
  margin-left: 2px;
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}

/* 流式输出时的消息样式 */
.message-item .ai-message .message-text {
  position: relative;
}

.message-item .ai-message[data-streaming="true"] .message-text {
  border-left: 3px solid #409eff;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  50% {
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
  }
  100% {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.typing-indicator {
  display: flex;
  gap: 4px;
  align-items: center;
}

/* 准备响应状态 */
.preparing-response {
  color: #999;
  font-style: italic;
  animation: fadeInOut 2s infinite;
}

@keyframes fadeInOut {
  0%, 100% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
}

/* AI思考内容样式 */
.thinking-section {
  margin-bottom: 12px;
  border: 1px solid #e0e7ff;
  border-radius: 8px;
  background-color: #f8faff;
  overflow: hidden;
}

.thinking-header {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background-color: #eef2ff;
  cursor: pointer;
  transition: background-color 0.2s ease;
  user-select: none;
}

.thinking-header:hover {
  background-color: #e0e7ff;
}

.thinking-icon {
  font-size: 12px;
  color: #6366f1;
  width: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.thinking-label {
  font-size: 13px;
  font-weight: 500;
  color: #4f46e5;
}

.thinking-hint {
  font-size: 11px;
  color: #9ca3af;
  margin-left: auto;
}

.thinking-content {
  padding: 12px;
  background-color: #f8faff;
  border-top: 1px solid #e0e7ff;
  font-size: 13px;
  line-height: 1.5;
  color: #6b7280;
  font-style: italic;
}

.thinking-content :deep(p) {
  margin: 4px 0;
}

.thinking-content :deep(ol),
.thinking-content :deep(ul) {
  margin: 8px 0;
  padding-left: 16px;
}

.thinking-content :deep(li) {
  margin: 2px 0;
}

.input-container {
  border-top: 1px solid #ebeef5;
  padding-top: 16px;
}

.input-wrapper {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.input-wrapper .el-textarea {
  flex: 1;
}

.send-button {
  height: 40px;
  padding: 0 20px;
}

.input-tips {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  text-align: right;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.form-container {
  margin-bottom: 16px;
}

.form-header {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background-color: #eef2ff;
  cursor: pointer;
  transition: background-color 0.2s ease;
  user-select: none;
}

.form-header:hover {
  background-color: #e0e7ff;
}

.form-title {
  font-size: 13px;
  font-weight: 500;
  color: #4f46e5;
}

.form-toggle {
  font-size: 12px;
  color: #9ca3af;
  width: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-fields {
  padding: 12px;
  background-color: #f8faff;
  border-top: 1px solid #e0e7ff;
  font-size: 13px;
  line-height: 1.5;
  color: #6b7280;
  font-style: italic;
}

.form-row {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.form-item-half {
  flex: 1;
}
</style> 